package com.qipay.admin.sp.controller;

import com.qipay.admin.BaseController;
import com.qipay.admin.login.AuthPassport;
import com.qipay.admin.sp.vo.SpUserDTO;
import com.qipay.baas.model.Sp;
import com.qipay.core.entity.Pagination;
import com.qipay.core.entity.Result;
import com.qipay.core.entity.ValueObject;
import com.qipay.core.help.BeanHelper;
import com.qipay.core.help.ResultHelper;
import com.qipay.order.service.OrderService;
import com.qipay.security.UserDetailsServiceImpl;
import com.qipay.sp.SpService;
import com.qipay.sp.SpUserService;
import com.qipay.sp.dto.SpUserOrderListDto;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Controller
@RequestMapping("/spUser")
public class SpUserController extends BaseController {

    @Autowired
    SpUserService spUserService;

    @Autowired
    SpService spService;

    @Autowired
    OrderService orderService;

    /**
     * 查询供号商,以sp,user,反查出User,
     *
     * @param loginUser
     * @return
     */
    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/query"}, method = RequestMethod.GET)
    public ModelAndView detail(
            @RequestParam(value = "p", required = false, defaultValue = "1") int p,
            @RequestParam(value = "pz", required = false, defaultValue = "10") int pz,
            @AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser
    ) {
        Pagination pagination = Pagination.instance(p, pz);
        List<ValueObject> query = spUserService.query(pagination);
        ModelAndView view = createModelAndView("spuser-list");
        List<SpUserDTO> spUserDTOS = BeanHelper.valueObjectToBean(query, SpUserDTO.class);
        view.addObject("spUsers", spUserDTOS);
        view.addObject("page", pagination);
        return view;
    }

    /**
     * 删除供号商,该供号商下面的没有SP,否则抛出异常
     *
     * @param loginUser
     * @return
     */
    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/delete"}, method = RequestMethod.POST)
    @ResponseBody
    public Result<String> delete(@RequestParam(value = "name", required = true) String name,
                                 @AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser
    ) {
        Result<String> resultSample = new Result<String>();

        try {
            SpUserDTO spUserDTO = new SpUserDTO();
            int status = spUserService.delete(name);
            return ResultHelper.success("删除成功");
        } catch (RuntimeException e) {
            return ResultHelper.error(e.getMessage());
        }
    }

    /**
     * 新增供号商
     *
     * @param loginUser
     * @return
     */
    @AuthPassport(key = "admin")
    @RequestMapping(value = {"/add"}, method = RequestMethod.POST)
    @ResponseBody
    public Result<String> userSave(
            @RequestParam(value = "spUserName", required = true) String spUserName,
            @AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser) {

        Result<String> resultSample = new Result<String>();

        try {
            SpUserDTO spUserDTO = new SpUserDTO();
            int status = spUserService.add(spUserName);
            return ResultHelper.success("添加成功");
        } catch (RuntimeException e) {
            return ResultHelper.error(e.getMessage());
        }
    }

    /**
     * 查询当前供号商下的,支付账号
     *
     * @param loginUser
     * @return
     */
    @RequestMapping(value = {"/spListQuery"}, method = RequestMethod.GET)
    @ResponseBody
    public ModelAndView spListQuery(
            @RequestParam(value = "from", required = false) String from,
            @RequestParam(value = "to", required = false) String to,
            @RequestParam(value = "p", required = false, defaultValue = "0") int p,
            @RequestParam(value = "pz", required = false, defaultValue = "10") int pz,
            @AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser) throws UnsupportedEncodingException {
        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        if (StringUtils.isBlank(from) || StringUtils.isBlank(to)) {
            Calendar calendar = Calendar.getInstance();
            from = format.format(calendar.getTime())+" 00:00";
            calendar.add(Calendar.DAY_OF_YEAR, 1);
            to = format.format(calendar.getTime())+" 00:00";
        }

        Pagination pagination = Pagination.instance(p, pz);
        List<Sp> spList = spService.findBySpUser(loginUser.getUsername(), pagination);
        Long total = orderService.sumOrderBySpUser(loginUser.getUsername(),from,to);
        if (spList!=null&&spList.size()>0){
            for (Sp sp:spList){
                Pagination pagination1 = Pagination.instance(1, 10000);
                SpUserOrderListDto res = spUserService.selectSpOrderList(sp.getId().intValue(), from, to, pagination1);
                sp.setCardNo(res.getTotalAmount().toString());
            }
        }
        String query = "?";
        Map<String, String> params = new HashMap<>();
        if (StringUtils.isNotBlank(from)) {
            query += String.format("&from=%s", URLEncoder.encode(from.toString(), "utf8"));
            params.put("from", from.toString());
        }
        if (StringUtils.isNotBlank(to)) {
            query += String.format("&to=%s", URLEncoder.encode(to.toString(), "utf8"));
            params.put("to", to.toString());
        }

        ModelAndView view = createModelAndView("spuser-splist");
        view.addObject("pagination", pagination);
        view.addObject("query", query);
        view.addObject("spList", spList);
        view.addObject("total",  new BigDecimal(total).divide(new BigDecimal(100)).toString());
        view.addObject("params", params);
        return view;
    }

    /**
     * 查询当前供号商下的,某个支付账号的流水
     * 以json返回,
     *
     * @param loginUser
     * @return
     */
    @RequestMapping(value = {"/orderListQuery"}, method = RequestMethod.POST)
    @ResponseBody
    public Result orderListQuery(
            @RequestParam(value = "spId", required = true) Integer spId,
            @RequestParam(value = "startTime", required = false) String startTime,
            @RequestParam(value = "endTime", required = false) String endTime,
            @RequestParam(value = "p", required = false, defaultValue = "1") int p,
            @RequestParam(value = "pz", required = false, defaultValue = "10") int pz,
            @AuthenticationPrincipal UserDetailsServiceImpl.LoginUserDetails loginUser) throws UnsupportedEncodingException {
        Pagination pagination = Pagination.instance(p, pz);
        SpUserOrderListDto res = spUserService.selectSpOrderList(spId, startTime, endTime, pagination);
        HashMap<String, Object> map = new HashMap<String, Object>();
        map.put("orders", res.getPageList());
        map.put("pagination", pagination);
        map.put("totalAmount",res.getTotalAmount());
        map.put("totalCount",res.getTotalCount());
        return ResultHelper.success("查询成功", map);
    }



}
